﻿using Abp.Application.Services.Dto;
using Abp.Domain.Repositories;
using Abp.EntityFrameworkCore.EFPlus;
using Abp.Extensions;
using Abp.Linq.Extensions;
using Abp.UI;
using ARchGL.Platform.Configuration;
using ARchGL.Platform.Core;
using ARchGL.Platform.Dtos;
using ARchGL.Platform.FileServer;
using ARchGL.Platform.Juneng;
using ARchGL.Platform.Juneng.ViewDtos;
using ARchGL.Platform.Utils;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace ARchGL.Platform.Application
{
    /// <summary>
    /// 图纸管理  实现
    /// </summary>
    public class DrawingsAppService : PlatformAppServiceBase//, IDrawingsAppService
    {
        private readonly IConfigurationRoot appConfiguration;
        private readonly IProjectsAppService projectsAppService;
        private readonly IRepository<ProjectDrawings, Guid> projectDrawingsRepository;
        private readonly IRepository<ProjectModels, Guid> modelsRepository;

        public DrawingsAppService(
            IHostingEnvironment env,
            IProjectsAppService _projectsAppService, IRepository<ProjectDrawings, Guid> _projectDrawingsRepository, IRepository<ProjectModels, Guid> _modelsRepository)
        {
            appConfiguration = env.GetAppConfiguration();
            projectsAppService = _projectsAppService;
            projectDrawingsRepository = _projectDrawingsRepository;
            modelsRepository = _modelsRepository;
        }

        #region 二维图纸模型

        /// <summary>
        /// 新建/编辑项目模型
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task CreatOrModifyModel(ProjectModelsDto input)
        {
            if (input.Id == Guid.Empty)
            {
                //if (input.TaskId == Guid.Empty) throw new UserFriendlyException("模型参数不正确", "请检查上传回传参数");
                var entity = ObjectMapper.Map<ProjectDrawings>(input);
#if !DEBUG
                entity.CreatorUserName = UserManager.UserName;
#endif
                entity.CreatorUserId = UserManager.PrimaryId;
                await projectDrawingsRepository.InsertAsync(entity);
            }
            //只编辑模型信息
            else
            {
                var entity = await projectDrawingsRepository.FirstOrDefaultAsync(x => x.Id == input.Id);
                if (entity == null) throw new UserFriendlyException(L("TheModelDoesNotExist"), L("PleaseRefreshThePageAndTryAgain"));
                entity.Name = input.Name;
                entity.ImageUrl = input.ImageUrl;
                entity.Size = input.Size;
                entity.ModelGroupId = input.ModelGroupId;
                entity.FileName = input.FileName;
                await projectDrawingsRepository.UpdateAsync(entity);
            }
        }

        /// <summary>
        /// 触发转换模型操作
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<dynamic> ConvertModel(ConvertModelsInput input)
        {
            var modelInfo = await projectDrawingsRepository.GetConvertModelList(input);

            //CIFileServer.AjaxResponse<dynamic> result1 = null;
            //try
            //{
            //    result1 = await cIFileServerApi.ConvertModel(projectInfo);
            //    return result1;
            //}
            //catch (Exception)
            //{

            //}
            //return result1;

            //var request = new RestRequest($"file/api/v1/FileConvert/convert-model/{input.ModelGroupId}", Method.POST, DataFormat.Json);
            //request.AddHeader("TenantId", Convert.ToBase64String(Encoding.UTF8.GetBytes(input.ProjectId.ToString())));
            //request.AddHeader("Authorization", RefreshTokenService.GetAccessToken());
            //request.AddJsonBody(modelInfo);
            //Logger.Info("\r\n#################################   调用转换输入参数：" + JsonConvert.SerializeObject(modelInfo));
            //var client = new RestClient(appConfiguration["App:FileServerRootAddress"]);//文件服务
            //var response = client.Execute(request);
            //Logger.Info($"\r\n#################################   调用转换：{response.StatusCode} " + response.Content);

            var response = await modelInfo.RequestConvertModel(appConfiguration, input.ModelGroupId, input.ProjectId, Logger);
            var flag = response.StatusCode == System.Net.HttpStatusCode.OK;
            if (flag)
            {
                var result = JsonConvert.DeserializeObject<SyncResult>(response.Content); //批量更新 TaskId，供前端判断转换进度时使用
                await projectDrawingsRepository.BatchUpdateAsync(x => new ProjectDrawings { TaskId = result.Item.BimTask.TaskId, Status = 1 },
                    x => x.ProjectId == input.ProjectId && x.ModelGroupId == input.ModelGroupId); //更新模型文件上的 TaskId
            }
            return response.Content;
        }

        /// <summary>
        /// 触发转换进度查询操作
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<bool> ConvertProcess(ConvertModelsInput input)
        {
            var modelInfo = await projectDrawingsRepository.GetConvertModelList(input);
            var responseArray = await modelInfo.RequestConvertProcess(appConfiguration, input.ModelGroupId, input.ProjectId, Logger);
            var result = false;
            foreach (var item in responseArray)
            {
                var flag = item?.StatusCode == System.Net.HttpStatusCode.OK;
                if (flag)
                {
                    var modelCouvertProcessApiDto = JsonConvert.DeserializeObject<ModelCouvertProcessResultItemApiDto>(item.Content)?.Item;
                    if (modelCouvertProcessApiDto.GetConvertStatus())
                    {
                        var asdf = modelInfo.FirstOrDefault(x => x.TaskId == modelCouvertProcessApiDto.TaskId);
                        if (asdf != null) asdf.ConvertStatus = 3;

                        await projectDrawingsRepository.BatchUpdateAsync(x => new ProjectDrawings { Status = 3 },
                            x => x.ProjectId == input.ProjectId && x.ModelGroupId == input.ModelGroupId); //更新模型文件上的 转换状态
                    }
                }
            }

            return result;
        }

        /// <summary>
        /// 删除模型
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task RemoveModel(Guid input)
        {
            var entity = await projectDrawingsRepository.FirstOrDefaultAsync(x => x.Id == input);
            if (entity == null) throw new UserFriendlyException(L("TheModelDoesNotExist"), L("PleaseRefreshThePageAndTryAgain"));
            await projectDrawingsRepository.DeleteAsync(entity);
        }

        /// <summary>
        /// 批量删除模型组模型
        /// </summary>
        /// <param name="modelGroupId">模型组标识</param>
        /// <returns></returns>
        public async Task BatchRemoveModelsByGroup(Guid modelGroupId)
        {
            await projectDrawingsRepository.DeleteAsync(x => x.ModelGroupId == modelGroupId);
        }

        /// <summary>
        /// 批量删除模型
        /// </summary>
        /// <param name="input">模型标识集合</param>
        /// <returns></returns>
        public async Task BatchRemoveModelsByIds(List<Guid> input)
        {
            if (input != null)
                await projectDrawingsRepository.DeleteAsync(x => input.Contains(x.Id));
        }

        /// <summary>
        /// 查询模型-分页数据集合
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<PagedResultDto<ProjectModelsDto>> QueryModelsPagedList(ProjectsModelsInput input)
        {
            var query = projectDrawingsRepository.GetAll()
                        .Where(x => x.ProjectId == input.ProjectId)
                        .WhereIf(!input.Filter.IsNullOrWhiteSpace(), x => x.Name.Contains(input.Filter))
                        .WhereIf(input.ModelGroupId != Guid.Empty, x => x.ModelGroupId == input.ModelGroupId);

            var result = await query.OrderByDescending(x => x.CreationTime).PageByAsync(input);

            return new PagedResultDto<ProjectModelsDto>(query.Count(),
                ObjectMapper.Map<List<ProjectModelsDto>>(result));
        }

        #endregion
    }
}
